package ca.camosun.chatbox.network.discovery;

import ca.camosun.chatbox.network.Room;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class BluetoothDiscovery {
	private final BluetoothAdapter mBluetoothAdapter;
	private final Context mContext;
	private Room<BluetoothDevice> mFoundSoFar;
	
	
	private OnCompletedDiscovery mOnCompletedCallback;
	private boolean mRunningDiscovery;

	// Create a BroadcastReceiver for ACTION_FOUND
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// When discovery finds a device
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// Get the BluetoothDevice object from the Intent
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				mFoundSoFar.people.add(device);
				
			} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
				assert mRunningDiscovery == false;
				mRunningDiscovery = true;
				
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				mRunningDiscovery = false;
				mOnCompletedCallback.execute(mFoundSoFar);
				mFoundSoFar = new Room<BluetoothDevice>();
			}
		}
	};

	public BluetoothDiscovery(Context context) {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		mContext = context;
		mFoundSoFar = new Room<BluetoothDevice>();
		mRunningDiscovery = false;
		
		// Register the BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		context.registerReceiver(mReceiver, filter);
	}
	
	public boolean discover(OnCompletedDiscovery callback) {
		if (mRunningDiscovery) {
			return false;
		}
		
		mOnCompletedCallback = callback;
		return mBluetoothAdapter.startDiscovery();
	}
	
	public void destroy() {
		mContext.unregisterReceiver(mReceiver);
	}
	
	public static interface OnCompletedDiscovery {
		void execute(Room<BluetoothDevice> foundDevices);
	}
}